package com.comac.print.component.app.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.comac.print.component.app.common.exception.PrintCommonException;
import com.comac.print.component.app.domain.PrintMasterplate;
import com.comac.print.component.app.domain.dto.PrintMasterplateSearchDTO;
import com.comac.print.component.app.mapper.PrintMasterplateMapper;
import com.comac.print.component.app.page.PageResponse;
import com.comac.print.component.app.service.PrintMasterplateService;
import com.comac.print.component.app.utils.NumUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 模板维护表 服务实现类
 * </p>
 *
 * @author zhoubin
 * @since 2025-04-16 03:51:14
 */
@Service
public class PrintMasterplateServiceImpl extends ServiceImpl<PrintMasterplateMapper, PrintMasterplate> implements PrintMasterplateService {


    @Autowired
    private PrintMasterplateMapper printMasterplateMapper;

    /**
     * 分页查询模板维护表
     *
     * @param searchDTO
     * @return
     */
    @Override
    public PageResponse<PrintMasterplate> searchPage(PrintMasterplateSearchDTO searchDTO) {
        LambdaQueryWrapper<PrintMasterplate> queryWrapper = createLambdaQueryWrapper(searchDTO);
        Page<PrintMasterplate> page = super.page(new Page<>(searchDTO.getPageNum(), searchDTO.getPageSize()),
                queryWrapper);
        return PageResponse.successPage(page);
    }

    /**
     * 新增模板，需要校验systemId + bussinessId是否已经存在
     *
     * @param entity PrintMasterplate
     * @return
     */
    @Override
    public boolean addPrintMasterplate(PrintMasterplate entity) {
        Date date = Date.from(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant());
        entity.setOperatorTime(date);

        if (StrUtil.isBlank(entity.getMpUrl())) {
            throw new PrintCommonException("模板地址为空，请先上传模板");
        }

        Integer count = countByIdAndName(entity);
        if (count != null && count > 0) {
            throw new PrintCommonException("模板id和名称已存在，无法新增，可升版！");
        }

        checkAndSetVersion(entity);
        entity.setFromVersion(null);

        return printMasterplateMapper.insert(entity) > 0;
    }

    private Integer countByIdAndName(PrintMasterplate entity) {
        LambdaQueryWrapper<PrintMasterplate> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(PrintMasterplate::getSystemId, entity.getSystemId())
                .eq(PrintMasterplate::getBussinessId, entity.getBussinessId());
        return printMasterplateMapper.selectCount(queryWrapper);
    }

    private void checkAndSetVersion(PrintMasterplate entity) {
        if (StrUtil.isNotBlank(entity.getVersion())) {
            //throw new PrintCommonException("不满足版本规则！");
        } else {
            throw new PrintCommonException("版本为空！");
        }
    }

    /**
     * 选择一个模板升版，需要传systemId + bussinessId，以及id
     *
     * @param entity PrintMasterplate
     * @return
     */
    @Override
    @Transactional(rollbackFor = Throwable.class)
    public boolean upgradePrintMasterplate(PrintMasterplate entity) {
        if (null == entity.getId() || entity.getId() < 0) {
            throw new PrintCommonException("请传基准版本");
        }

        if (StrUtil.isBlank(entity.getSystemId()) || StrUtil.isBlank(entity.getBussinessId())) {
            throw new PrintCommonException("缺少模板ID或模板名称");
        }

        Date date = Date.from(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant());
        entity.setOperatorTime(date);

        if (StrUtil.isBlank(entity.getMpUrl())) {
            throw new PrintCommonException("模板地址为空，请先上传模板");
        }

        Integer count = countByIdAndName(entity);
        if (count == null || count <= 0) {
            throw new PrintCommonException("基准版本不存在，id：" + entity.getId()
                    + ", 模板名称：" + entity.getSystemId()
                    + ", 模板ID：" + entity.getSystemId());
        }
        //checkValidTime(entity);

        if (StrUtil.isBlank(entity.getFromVersion())) {
            throw new PrintCommonException("FromVersion版本为空！");
        }

        entity.setVersion(NumUtil.addNum(entity.getFromVersion()));

        //逻辑删除旧版本
        printMasterplateMapper.deleteById(entity.getId());

        //插入升版后的数据
        entity.setId(null);
        return printMasterplateMapper.insert(entity) > 0;
    }

    private void checkValidTime(PrintMasterplate entity) {
        LambdaQueryWrapper<PrintMasterplate> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(PrintMasterplate::getSystemId, entity.getSystemId())
                .eq(PrintMasterplate::getBussinessId, entity.getBussinessId());
        queryWrapper.between(PrintMasterplate::getValidStart, entity.getValidStart(), entity.getValidEnd())
                .or()
                .between(PrintMasterplate::getValidEnd, entity.getValidStart(), entity.getValidEnd());
        Integer validCount = printMasterplateMapper.selectCount(queryWrapper);
        if(validCount != null && validCount > 0){
            throw new PrintCommonException("升版时间重复，请检查");
        }
    }

    /**
     * 查询历史版本，需要传systemId + bussinessId
     *
     * @param entity PrintMasterplate
     * @return
     */
    @Override
    public List<PrintMasterplate> getHistoryPrintMasterplate(PrintMasterplate entity) {
        List<PrintMasterplate> historyList = printMasterplateMapper.selectDeletedList(entity);
        return historyList;
    }

    private LambdaQueryWrapper<PrintMasterplate> createLambdaQueryWrapper(PrintMasterplateSearchDTO searchDTO) {
        LambdaQueryWrapper<PrintMasterplate> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.like(StrUtil.isNotBlank(searchDTO.getSystemId()),
                        PrintMasterplate::getSystemId, searchDTO.getSystemId())
                .eq(StrUtil.isNotBlank(searchDTO.getBussinessId()),
                        PrintMasterplate::getBussinessId, searchDTO.getBussinessId())
                .eq(StrUtil.isNotBlank(searchDTO.getVersion()),
                        PrintMasterplate::getVersion, searchDTO.getVersion())
                .eq(StrUtil.isNotBlank(searchDTO.getFromVersion()),
                        PrintMasterplate::getFromVersion, searchDTO.getFromVersion())
                .like(StrUtil.isNotBlank(searchDTO.getMpUrl()),
                        PrintMasterplate::getMpUrl, searchDTO.getMpUrl())
                .eq(StrUtil.isNotBlank(searchDTO.getOperator()),
                        PrintMasterplate::getOperator, searchDTO.getOperator())
                .like(StrUtil.isNotBlank(searchDTO.getOperatorName()),
                        PrintMasterplate::getOperatorName, searchDTO.getOperatorName())
                .between(null != searchDTO.getOperatorBeginTime() && null != searchDTO.getOperatorEndTime(),
                        PrintMasterplate::getOperatorTime, searchDTO.getOperatorBeginTime(), searchDTO.getOperatorEndTime());
        queryWrapper.orderByDesc(PrintMasterplate::getOperatorTime);
        return queryWrapper;
    }


}
